package com.hoshiibuy.company.service.impl;


import com.hoshiibuy.common.exception.CommonError;
import com.hoshiibuy.common.exception.ServiceException;
import com.hoshiibuy.company.entity.ComUsers;
import com.hoshiibuy.company.feign.IdGeneratorService;
import com.hoshiibuy.company.mapper.IComUsersMapper;
import com.hoshiibuy.company.service.IComUsersService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;

/**
 * <p>
 * 公司用户基本信息表 服务实现类
 * </p>
 *
 * @author WGJ
 * @since 2019-04-24
 */
@Service
public class ComUsersServiceImpl extends ServiceImpl<IComUsersMapper, ComUsers> implements IComUsersService {

    @Autowired
    private IdGeneratorService idGeneratorService;

    /**
     * @param id
     * @return com.hoshiibuy.com
     * @description: 根据id查询平台信息
     */
    @Cacheable(cacheNames = "companyusers", key = "#root.targetClass.simpleName+':'+#root.methodName+':'+#id")
    @Override
    public ComUsers getById(Long id) {
        return baseMapper.selectById(id);
    }


    /**
     * @param
     * @return boolean
     * @description: 新增公司用户基本
     */
    @Transactional(rollbackFor = Exception.class)
    @CacheEvict(cacheNames = "companyusers", allEntries = true)
    @Override
    public boolean save(ComUsers entity) {

        String id = idGeneratorService.queryGeneratorId();

        if (id == null) {
            throw new ServiceException(CommonError.error("新增公司用户基本失败"));
        }
        entity.setId(Long.parseLong(id));
        entity.setCreatedtime(LocalDateTime.now());
        entity.setModifiedtime(LocalDateTime.now());

        /**
         * 设置日期参数
         */
        entity.setBirthdayTime(LocalDateTime.now());
        entity.setLastLoginTime(LocalDateTime.now());
        int row = baseMapper.insert(entity);
        if (row <= 0) {
            throw new ServiceException(CommonError.error("新增公司用户基本失败"));
        }
        return true;
    }

    /**
     * @param entity
     * @return boolean
     * @description: 修改公司用户基本信息
     */
    @Transactional(rollbackFor = Exception.class)
    @CacheEvict(cacheNames = "companyusers", allEntries = true)
    @Override
    public boolean updateById(ComUsers entity) {

        entity.setModifiedtime(LocalDateTime.now());
        int row = baseMapper.updateById(entity);
        if (row <= 0) {
            throw new ServiceException(CommonError.error("修改公司用户基本失败"));
        }
        return true;
    }
}